package chenshuaiwen.service.impl;

import chenshuaiwen.dao.IDeptDao;
import chenshuaiwen.dao.collection.DeptDao;
import chenshuaiwen.domain.dto.DeptDto;
import chenshuaiwen.domain.entity.Dept;
import chenshuaiwen.domain.vo.DeptVo;
import chenshuaiwen.domain.vo.Result;
import chenshuaiwen.service.IDeptService;
import chenshuaiwen.service.IUserService;
import chenshuaiwen.util.SingletonFactory;

import java.time.LocalDateTime;


/**
 * 业务层-部门
 *
 * @author 陈帅闻
 * @since 2025/4/20 15:19
 */

public class DeptService extends BaseService<Dept, DeptDto, DeptVo, IDeptDao> implements IDeptService{

    private IUserService userService;

    private DeptService(){
        dao = SingletonFactory.getInstance(DeptDao.class);
        temp = new DeptVo[0];
    }

    @Override
    DeptVo convertToVo(Dept dept){
        return new DeptVo(dept.getId(), dept.createAt, dept.updateAt, dept.name, dept.phone);
    }

    @Override
    Dept createEntity(DeptDto dto){
        LocalDateTime now = LocalDateTime.now();
        return new Dept(null, now, now, dto.name, dto.phone);
    }

    @Override
    void updateEntity(DeptDto dto,Dept dept){
        dept.updateAt = LocalDateTime.now();
        dept.name = dto.name;
        dept.phone = dto.phone;
    }

    @Override
    public Result delete(int id) {
        if(!existsById(id)){
            return Result.failure("删除失败，不存在该数据");
        }
        if(userService == null){
            userService = SingletonFactory.getInstance(UserService.class);
        }
        if(userService.deptInUse(id)){
            return Result.failure("删除失败，还有用户属于该部门，不能删除");
        }
        dao.delete(id);
        return Result.success("删除成功", null);
    }

}
